<template>
  <div class="employee-management">
    <div class="table-header">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索员工姓名"
        style="width: 300px"
        clearable
        filterable
        @clear="handleSearch"
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
          </el-button>
        </template>
      </el-input>
      <div class="downs">
        <!-- <el-button type="primary" style="margin: 0 5px" @click="downloadMode"
          >下载模板</el-button
        >
        <el-button
          type="primary"
          style="margin: 0 5px"
          @click="dialogVisible = !dialogVisible"
          >同步</el-button
        >
        <el-upload
          class="single-button-upload"
          :auto-upload="false"
          :limit="1"
          :on-exceed="handleExceed"
          :before-upload="beforeUpload"
          :on-change="handleChange"
          :show-file-list="false"
          accept=".xlsx,.xls"
        >
          <el-button type="primary" :loading="uploading" style="margin: 0 5px">
            <el-icon v-if="!uploading" style="margin-right: 5px">
              <Upload />
            </el-icon>
            {{ getButtonText() }}
          </el-button>
        </el-upload> -->
      </div>
    </div>

    <el-dialog v-model="dialogVisible" title="同步" width="500">
      <div>
        <el-select
          v-model="tbvalue"
          placeholder="请选择要同步数据的平台"
          style="width: 240px"
        >
          <el-option
            v-for="item in tboptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="tongbu"> 开始同步 </el-button>
        </div>
      </template>
    </el-dialog>

    <el-table
      :data="filteredEmployees"
      style="width: 100%"
      v-loading="loading"
      stripe
    >
      <el-table-column type="index" label="员工ID" width="100" align="center" />
      <el-table-column prop="name" label="姓名" width="120" align="center" />
      <el-table-column
        prop="education"
        label="学历"
        width="120"
        align="center"
      />
      <el-table-column
        prop="workYears"
        label="工作年限"
        width="100"
        align="center"
      />
      <el-table-column
        prop="department"
        label="部门"
        width="120"
        align="center"
      />
      <el-table-column
        prop="position"
        label="岗位"
        width="120"
        align="center"
      />
      <el-table-column
        prop="email"
        label="邮箱"
        min-width="120"
        align="center"
      />
      <el-table-column prop="phone" label="电话" width="120" align="center" />
      <el-table-column label="操作" width="250" fixed="right" align="center">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            link
            @click="$emit('view-resume', scope.row)"
          >
            预览简历
          </el-button>
          <!-- <el-button
            size="small"
            type="primary"
            link
            @click="$emit('edit-employee', scope.row)"
          >
            编辑
          </el-button> -->
          <!-- <el-button
            size="small"
            type="danger"
            link
            @click="$emit('delete-employee', scope.row)"
          >
            删除
          </el-button> -->
          <el-button size="small" type="primary" link @click="allYG(scope.row)">
            员工综合视图
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog v-model="dialogVisible2" title="员工综合视图" width="1000">
      <div>
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="姓名">{{
            selectedEmployee.employee ? selectedEmployee.employee.name : ""
          }}</el-descriptions-item>
          <el-descriptions-item label="学历">{{
            selectedEmployee.employee ? selectedEmployee.employee.education : ""
          }}</el-descriptions-item>
          <el-descriptions-item label="工作年限"
            >{{
              selectedEmployee.employee
                ? selectedEmployee.employee.workYears
                : ""
            }}年</el-descriptions-item
          >
          <el-descriptions-item label="当前岗位">{{
            selectedEmployee.employee ? selectedEmployee.employee.position : ""
          }}</el-descriptions-item>
          <el-descriptions-item label="部门">{{
            selectedEmployee.employee
              ? selectedEmployee.employee.department
              : ""
          }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{
            selectedEmployee.employee ? selectedEmployee.employee.email : ""
          }}</el-descriptions-item>
          <el-descriptions-item label="电话">{{
            selectedEmployee.employee ? selectedEmployee.employee.phone : ""
          }}</el-descriptions-item>
          <el-descriptions-item label="入职日期">{{
            selectedEmployee.employee ? selectedEmployee.employee.joinDate : ""
          }}</el-descriptions-item>
        </el-descriptions>

        <!-- 培训记录 -->
        <div class="section">
          <div style="display: flex; justify-content: space-between">
            <h3>培训记录</h3>
            <router-link
              :to="{
                path: '/employee-data',
              }"
              style="
                color: #409eff;
                text-decoration: none !important;
                margin-right: 15px;
              "
              >数据追溯</router-link
            >
          </div>

          <el-table
            :data="
              selectedEmployee.employee
                ? selectedEmployee.employee.trainingRecords
                : ''
            "
            style="width: 100%"
            v-loading="loading"
          >
            <el-table-column prop="courseName" label="课程名称" />
            <el-table-column prop="courseType" label="课程类型" />
            <el-table-column prop="trainingDate" label="培训日期" width="120" />
            <el-table-column prop="score" label="考核分数" width="100">
              <template #default="scope">
                <el-tag :type="getScoreType(scope.row.score)">
                  {{ scope.row.score }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              prop="trainingHours"
              label="培训时长"
              width="100"
            />
            <el-table-column prop="instructor" label="讲师" />
            <el-table-column prop="status" label="状态" width="80">
              <template #default="scope">
                <el-tag
                  :type="scope.row.status === '已完成' ? 'success' : 'warning'"
                >
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 绩效数据 -->
        <div class="section">
          <div style="display: flex; justify-content: space-between">
            <h3>绩效记录</h3>
            <router-link
              :to="{
                path: '/employee-data',
              }"
              style="
                color: #409eff;
                text-decoration: none !important;
                margin-right: 15px;
              "
              >数据追溯</router-link
            >
          </div>
          <el-table
            :data="selectedEmployee.performances"
            style="width: 100%"
            v-loading="loading"
          >
            <el-table-column prop="period" label="考核周期" width="120" />
            <el-table-column
              prop="evaluationDate"
              label="评估日期"
              width="120"
            />
            <el-table-column prop="overallScore" label="综合评分" width="120">
              <template #default="scope">
                <el-rate
                  v-model="scope.row.overallScore"
                  disabled
                  show-score
                  text-color="#ff9900"
                  score-template="{value}"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="leadershipScore"
              label="绩效领导力"
              width="100"
            >
              <template #default="scope">
                <el-rate
                  v-model="scope.row.leadershipScore"
                  disabled
                  show-score
                  text-color="#ff9900"
                  score-template="{value}"
                />
              </template>
            </el-table-column>
            <el-table-column prop="technicalScore" label="技术能力" width="100">
              <template #default="scope">
                <el-rate
                  v-model="scope.row.technicalScore"
                  disabled
                  show-score
                  text-color="#ff9900"
                  score-template="{value}"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="communicationScore"
              label="人际交往能力"
              width="100"
            >
              <template #default="scope">
                <el-rate
                  v-model="scope.row.communicationScore"
                  disabled
                  show-score
                  text-color="#ff9900"
                  score-template="{value}"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="achievements"
              label="主要成果"
              show-overflow-tooltip
            />
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from "vue";
import api from "@/services/api";
import { ElMessage, ElMessageBox } from "element-plus";
// import { Upload, Document } from '@element-plus/icons-vue'
import axios from "axios";

export default {
  name: "EmployeeManagement",
  props: {
    employees: {
      type: Array,
      default: () => [],
    },
  },
  emits: ["edit-employee", "delete-employee", "view-resume"],
  setup(props) {
    const searchKeyword = ref("");
    const currentPage = ref(1);
    const pageSize = ref(20);
    const loading = ref(false);
    const fileList = ref([]);
    const uploading = ref(false);
    const uploadResult = ref("");

    const filteredEmployees = ref([]);
    const dialogVisible = ref(false);
    const tbvalue = ref("");
    const selectedEmployee = ref([]);
    const tboptions = ref([
      {
        label: "企业",
        value: "qiye",
      },
      {
        label: "其他平台",
        value: "other",
      },
    ]);
    const dialogVisible2 = ref(false);

    onMounted(() => {
      console.log(props.employees);

      onload();
    });

    const getScoreType = (score) => {
      if (score >= 9) return "success";
      if (score >= 7) return "warning";
      return "danger";
    };

    const allYG = (row) => {
      dialogVisible2.value = true;
      console.log(row.id, "row.id");

      onEmployeeChange(row.id);
    };

    const onEmployeeChange = async (employeeId) => {
      try {
        const response = await api.getEmployeeData(employeeId);
        selectedEmployee.value = response.data;
        console.log(selectedEmployee.value, "selectedEmployee.value");
      } catch (error) {
        ElMessage.error("加载员工数据失败");
      }
    };

    watch(
      () => props.employees,
      (newId, oldId) => {
        console.log("userId 发生变化:", oldId, "→", newId);
        // 执行相关操作，比如重新加载数据
        onload();
      }
    );

    const onload = async () => {
      try {
        const resEmployees = await api.getEmployees();
        filteredEmployees.value = resEmployees.data;
      } catch (error) {
        console.error("加载员工数据失败:", error);
      }
    };

    const total = computed(() => {
      if (searchKeyword.value) {
        return props.employees.filter((employee) =>
          employee.name.includes(searchKeyword.value)
        ).length;
      }
      return props.employees.length;
    });

    const tongbu = async () => {
      try {
        await api.createEmployee({
          name: "李凯",
          education: "本科",
          workYears: 2,
          department: "项目部1",
          position: "软件开发",
          email: "likai@126.com",
          phone: "17630038239",
          joinDate: "2025-11-05",
          resume: "员工简历",
        });
        dialogVisible.value = false;
      } catch (error) {
        dialogVisible.value = false;
      }
      try {
        await api.createEmployee({
          id: 67,
          name: "王桂懒",
          education: "本科",
          workYears: 5,
          department: "技术部",
          position: "软件工程师",
          resume:
            "苏宁易购集团股份有限公司（2020.09 - 2021.5） - 系统架构师\n主导苏宁易购电商平台的架构升级，采用分布式微服务架构，提升了系统的可扩展性和容错性，能够应对更高的并发流量，大促期间系统吞吐量提升 2 倍。负责系统的技术选型与团队技术培训，提高了团队整体技术水平。\n唯品会（中国）有限公司（2018.05 - 2020.08） - 系统架构师\n参与唯品会物流系统架构设计，引入消息队列和缓存技术，优化了订单处理流程，使订单处理速度提高 50%。负责系统的性能调优和监控方案制定，保障了物流系统的稳定运行。",
          email: "wangguiflan@example.net",
          phone: "1523829835",
          joinDate: "2023-12-12",
          trainingRecords: [],
        });
      } catch (error) {}
      try {
        await api.createEmployee({
          id: 66,
          name: "王桂芳",
          education: "本科",
          workYears: 5,
          department: "技术部",
          position: "软件工程师",
          resume:
            "苏宁易购集团股份有限公司（2020.09 - 2021.5） - 系统架构师\n主导苏宁易购电商平台的架构升级，采用分布式微服务架构，提升了系统的可扩展性和容错性，能够应对更高的并发流量，大促期间系统吞吐量提升 2 倍。负责系统的技术选型与团队技术培训，提高了团队整体技术水平。\n唯品会（中国）有限公司（2018.05 - 2020.08） - 系统架构师\n参与唯品会物流系统架构设计，引入消息队列和缓存技术，优化了订单处理流程，使订单处理速度提高 50%。负责系统的性能调优和监控方案制定，保障了物流系统的稳定运行。",
          email: "wangguifang@example.net",
          phone: "1523829834",
          joinDate: "2023-12-12",
          trainingRecords: [],
        });
        onload();
        ElMessage.success(`信息同步成功`);
      } catch (error) {
        ElMessage.error(`信息同步失败`);
      }
    };

    const handleSearch = async () => {
      currentPage.value = 1;

      await api
        .searchEmployees(searchKeyword.value)
        .then((response) => {
          filteredEmployees.value = response.data;
        })
        .catch((error) => {
          console.error("搜索员工失败:", error);
        });
    };

    const handleSizeChange = (newSize) => {
      pageSize.value = newSize;
      currentPage.value = 1;
    };

    const handleCurrentChange = (newPage) => {
      currentPage.value = newPage;
    };

    const importError = (file, uploadFiles) => {
      ElMessage.error(`${file.name} 上传失败`);
    };

    const importSuccess = (uploadFile) => {
      ElMessage.success(`${uploadFile.name} 上传成功`);
    };

    const downloadMode = async () => {
      try {
        const response = await axios.get(
          "http://192.168.100.167:8080/api/excel/template/employees",
          {
            responseType: "blob",
          }
        );

        if (response) {
          // 创建 blob
          const blob = new Blob([response.data]);
          const url = window.URL.createObjectURL(blob);

          // 创建下载链接
          const link = document.createElement("a");
          link.href = url;
          link.download = getFilename(response);

          // 添加到 DOM 并触发点击
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);

          // 清理
          window.URL.revokeObjectURL(url);
        }
      } catch (error) {
        console.error("下载失败:", error);
        alert("下载失败，请重试");
      }
    };

    const getFilename = (response) => {
      const disposition = response.headers["content-disposition"];
      if (disposition && disposition.indexOf("attachment") !== -1) {
        const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
        const matches = filenameRegex.exec(disposition);
        if (matches != null && matches[1]) {
          return matches[1].replace(/['"]/g, "");
        }
      }
      return "员工基本信息导入模板.xlsx";
    };

    // 当前选择的文件
    const currentFile = computed(() => {
      return fileList.value.length > 0 ? fileList.value[0] : null;
    });

    // 监听 currentFile 变化，有值时自动触发上传
    watch(currentFile, (newFile, oldFile) => {
      if (newFile && !oldFile) {
        // 从无到有选择了文件，自动触发上传
        console.log("检测到文件选择，自动触发上传:", newFile.name);
        handleUpload();
      }
    });

    // 获取按钮文本
    const getButtonText = () => {
      if (uploading.value) {
        return "上传中...";
      }
      return "导入";
    };

    // 文件选择变化
    const handleChange = (file, files) => {
      fileList.value = files;
      uploadResult.value = ""; // 清空上传结果
    };

    // 文件超出限制
    const handleExceed = () => {
      ElMessage.warning("只能上传一个文件");
    };

    // 上传前的验证
    const beforeUpload = (file) => {
      const isExcel = file.name.endsWith(".xlsx") || file.name.endsWith(".xls");
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isExcel) {
        ElMessage.error("只能上传Excel文件!");
        // 清空无效文件
        setTimeout(() => {
          fileList.value = [];
        }, 100);
        return false;
      }
      if (!isLt10M) {
        ElMessage.error("文件大小不能超过10MB!");
        // 清空过大文件
        setTimeout(() => {
          fileList.value = [];
        }, 100);
        return false;
      }

      console.log("文件验证通过:", file.name);
      return true;
    };

    // 格式化文件大小
    // const formatFileSize = (bytes) => {
    //   if (bytes === 0) return '0 B'
    //   const k = 1024
    //   const sizes = ['B', 'KB', 'MB', 'GB']
    //   const i = Math.floor(Math.log(bytes) / Math.log(k))
    //   return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    // }

    // 上传函数
    const handleUpload = async () => {
      if (!currentFile.value) {
        ElMessage.warning("请先选择文件");
        return;
      }

      // 再次验证文件
      if (!beforeUpload(currentFile.value)) {
        return;
      }

      uploading.value = true;
      uploadResult.value = "";

      try {
        const formData = new FormData();
        formData.append("file", currentFile.value.raw);

        console.log("开始上传文件:", currentFile.value.name);

        const response = await axios.post(
          "http://192.168.100.167:8080/api/excel/import/employees",
          formData,
          {
            headers: {
              "Content-Type": "multipart/form-data",
            },
            timeout: 30000,
            onUploadProgress: (progressEvent) => {
              if (progressEvent.total) {
                const progress = Math.round(
                  (progressEvent.loaded * 100) / progressEvent.total
                );
                console.log(`上传进度: ${progress}%`);
              }
            },
          }
        );

        // 上传成功
        ElMessage.success("文件上传成功");
        fileList.value = [];
        uploadResult.value = "上传成功";
        onload();
        console.log("上传响应:", response.data);

        // 上传成功后的回调
        handleUploadSuccess(response.data);
      } catch (error) {
        // 上传失败
        let errorMessage = "文件上传失败";
        if (error.response) {
          errorMessage = error.response.data?.message || errorMessage;
          console.error(
            "服务器错误:",
            error.response.status,
            error.response.data
          );
        } else if (error.request) {
          errorMessage = "网络错误，请检查网络连接";
          console.error("网络错误:", error.request);
        } else {
          console.error("请求错误:", error.message);
        }

        ElMessage.error(errorMessage);
        uploadResult.value = "上传失败";

        // 上传失败后的回调
        handleUploadError(error);
      } finally {
        uploading.value = false;

        // 3秒后清空文件列表
        setTimeout(() => {
          fileList.value = [];
          uploadResult.value = "";
        }, 3000);
      }
    };

    // 上传成功处理
    const handleUploadSuccess = (responseData) => {
      // 可以在这里处理上传成功后的业务逻辑
      // 例如：刷新列表、显示成功信息等
      console.log("上传成功处理:", responseData);

      // 触发自定义事件，通知父组件
      // emit('upload-success', responseData)
    };

    // 上传失败处理
    const handleUploadError = (error) => {
      // 可以在这里处理上传失败后的业务逻辑
      console.error("上传失败处理:", error);

      // 触发自定义事件，通知父组件
      // emit('upload-error', error)
    };

    return {
      searchKeyword,
      currentPage,
      pageSize,
      loading,
      filteredEmployees,
      total,
      handleSearch,
      handleSizeChange,
      handleCurrentChange,
      importError,
      importSuccess,
      downloadMode,
      getButtonText,
      handleChange,
      handleExceed,
      beforeUpload,
      handleUpload,
      handleUploadSuccess,
      handleUploadError,
      uploading,
      tongbu,
      dialogVisible,
      tboptions,
      tbvalue,
      allYG,
      dialogVisible2,
      selectedEmployee,
      getScoreType,
    };
  },
};
</script>

<style scoped>
.employee-management {
  padding: 20px 0;
}

.table-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.downs {
  display: flex;
  justify-content: end;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
